const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');

const menuFilePath = path.join(__dirname, '../json/menuData.json');

// 读取菜单数据
const readMenuData = (filePath) => {
    const data = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(data);
};

// 写入菜单数据
const writeMenuData = (filePath, data) => {
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
};

// 获取菜单（带鉴权）
exports.getMenu = (req, res) => {
    const authHeader = req.headers['authorization'];
    if (!authHeader) {
        return res.status(401).json({ code: 1, message: '缺少授权头' });
    }

    const token = authHeader.split(' ')[1];
    if (!token) {
        return res.status(401).json({ code: 1, message: 'Token 不存在' });
    }

    jwt.verify(token, 'your_secret_key', (err) => {
        if (err) {
            return res.status(403).json({ code: 1, message: 'Token 无效或已过期' });
        }

        const menuData = readMenuData(menuFilePath);
        res.json({ code: 0, message: '获取菜单成功', content: menuData });
    });
};

// 新增顶级菜单
exports.addTopMenu = (req, res) => {
    const authHeader = req.headers['authorization'];
    if (!authHeader) {
        return res.status(401).json({ code: 1, message: '缺少授权头' });
    }

    const token = authHeader.split(' ')[1];
    if (!token) {
        return res.status(401).json({ code: 1, message: 'Token 不存在' });
    }

    jwt.verify(token, 'your_secret_key', (err) => {
        if (err) {
            return res.status(403).json({ code: 1, message: 'Token 无效或已过期' });
        }

        const { title, icon } = req.body;
        if (!title || !icon) {
            return res.status(400).json({ code: 1, message: '缺少 title 或 icon 参数' });
        }

        const menuData = readMenuData(menuFilePath);
        const newId = Math.max(...menuData.map(item => item.id)) + 1;

        const newTopMenu = {
            id: newId,
            title,
            icon,
            path: `/menu${newId}`,
            type: 1,
            children: []
        };

        menuData.push(newTopMenu);
        writeMenuData(menuFilePath, menuData);

        res.json({ code: 0, message: '新增顶级菜单成功', content: newTopMenu });
    });
};

// 新增二级菜单
exports.addSubMenu = (req, res) => {
    const authHeader = req.headers['authorization'];
    if (!authHeader) {
        return res.status(401).json({ code: 1, message: '缺少授权头' });
    }

    const token = authHeader.split(' ')[1];
    if (!token) {
        return res.status(401).json({ code: 1, message: 'Token 不存在' });
    }

    jwt.verify(token, 'your_secret_key', (err) => {
        if (err) {
            return res.status(403).json({ code: 1, message: 'Token 无效或已过期' });
        }

        const { title, icon, path: subPath, parentId } = req.body;
        if (!title || !icon || !subPath || !parentId) {
            return res.status(400).json({ code: 1, message: '缺少必要参数' });
        }

        const menuData = readMenuData(menuFilePath);
        const parentMenu = menuData.find(item => item.id === Number(parentId));

        if (!parentMenu) {
            return res.status(404).json({ code: 1, message: '未找到对应的顶级菜单' });
        }

        const allIds = menuData.flatMap(item => [item.id, ...(item.children || []).map(c => c.id)]);
        const newId = Math.max(...allIds) + 1;

        const newSubMenu = {
            id: newId,
            title,
            icon,
            path: subPath,
            type: 2,
            children: []
        };

        parentMenu.children = parentMenu.children || [];
        parentMenu.children.push(newSubMenu);

        writeMenuData(menuFilePath, menuData);

        res.json({ code: 0, message: '新增二级菜单成功', content: newSubMenu });
    });
};

// 编辑菜单（支持顶级和二级）
exports.editMenu = (req, res) => {
    const authHeader = req.headers['authorization'];
    if (!authHeader) {
        return res.status(401).json({ code: 1, message: '缺少授权头' });
    }

    const token = authHeader.split(' ')[1];
    if (!token) {
        return res.status(401).json({ code: 1, message: 'Token 不存在' });
    }

    jwt.verify(token, 'your_secret_key', (err) => {
        if (err) {
            return res.status(403).json({ code: 1, message: 'Token 无效或已过期' });
        }

        const { id, title, icon, path: newPath } = req.body;
        if (!id || !title || !icon) {
            return res.status(400).json({ code: 1, message: '缺少必要参数' });
        }

        const menuData = readMenuData(menuFilePath);
        let updated = false;

        for (const menu of menuData) {
            if (menu.id === Number(id)) {
                menu.title = title;
                menu.icon = icon;
                if (newPath) menu.path = newPath;
                updated = true;
                break;
            }
            if (menu.children && menu.children.length > 0) {
                for (const child of menu.children) {
                    if (child.id === Number(id)) {
                        child.title = title;
                        child.icon = icon;
                        if (newPath) child.path = newPath;
                        updated = true;
                        break;
                    }
                }
            }
        }

        if (!updated) {
            return res.status(404).json({ code: 1, message: '未找到对应的菜单' });
        }

        writeMenuData(menuFilePath, menuData);
        res.json({ code: 0, message: '菜单更新成功' });
    });
};


// 删除菜单（支持删除顶级和二级菜单）
exports.deleteMenu = (req, res) => {
    const authHeader = req.headers['authorization'];
    if (!authHeader) {
        return res.status(401).json({ code: 1, message: '缺少授权头' });
    }

    const token = authHeader.split(' ')[1];
    if (!token) {
        return res.status(401).json({ code: 1, message: 'Token 不存在' });
    }

    jwt.verify(token, 'your_secret_key', (err) => {
        if (err) {
            return res.status(403).json({ code: 1, message: 'Token 无效或已过期' });
        }

        const { id } = req.body;
        if (!id) {
            return res.status(400).json({ code: 1, message: '缺少菜单ID' });
        }

        let menuData = readMenuData(menuFilePath);
        let deleted = false;

        // 删除顶级菜单
        const topLevelIndex = menuData.findIndex(item => item.id === Number(id));
        if (topLevelIndex !== -1) {
            menuData.splice(topLevelIndex, 1);
            deleted = true;
        } else {
            // 删除二级菜单
            for (const menu of menuData) {
                if (menu.children && menu.children.length > 0) {
                    const childIndex = menu.children.findIndex(c => c.id === Number(id));
                    if (childIndex !== -1) {
                        menu.children.splice(childIndex, 1);
                        deleted = true;
                        break;
                    }
                }
            }
        }

        if (!deleted) {
            return res.status(404).json({ code: 1, message: '未找到对应的菜单' });
        }

        writeMenuData(menuFilePath, menuData);
        res.json({ code: 0, message: '菜单删除成功' });
    });
};




